//
//  UploadTool.m
//  MyDemo
//
//  Created by macOS on 2016/12/6.
//  Copyright © 2016年 macOS. All rights reserved.
//

#import "UploadTool.h"
#import "AFNetworking.h"
#import "MBProgressHUD.h"
#import "WCPopupLayerManager.h"
@implementation UploadTool


+ (void)uploadImageWithUrl:(NSString *)url withZip:(NSString *)zip withParas:(NSDictionary *)params  withSuccess:(void(^)())successBlock withFail:(void(^)())failBlock{
    
   
    
    NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
    if (!token) {
        [[WCPopupLayerManager shareMg] showTextOnly:@"没有登陆~" withView:[UIApplication sharedApplication].keyWindow];
        return;
    }
    
    
    MBProgressHUD *hud = [[WCPopupLayerManager shareMg] showProgressToView:[UIApplication sharedApplication].keyWindow];
    /*
     此段代码如果需要修改，可以调整的位置
     1. 把upload.php改成网站开发人员告知的地址
     2. 把file改成网站开发人员告知的字段名
     */
    
    //AFN3.0+基于封住HTPPSession的句柄
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //设置token到请求头部 [manager.requestSerializer setValue:token forHTTPHeaderField:@"token"];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/plain",@"text/html",nil];
    NSString *token_value = [NSString stringWithFormat:@"Bearer %@",token] ;
     [manager.requestSerializer setValue:token_value forHTTPHeaderField:@"Authorization"];
    //formData: 专门用于拼接需要上传的数据,在此位置生成一个要上传的数据体
       [manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
       
        
        NSData *data = [NSData dataWithContentsOfFile:zip];
        
        // 在网络开发中，上传文件时，是文件不允许被覆盖，文件重名
        // 要解决此问题，
        // 可以在上传时使用当前的系统事件作为文件名
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        // 设置时间格式
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.zip", str];
        
        //上传
        /*
         此方法参数
         1. 要上传的[二进制数据]
         2. 对应网站上[upload.php中]处理文件的[字段"file"]
         3. 要保存在服务器上的[文件名]
         4. 上传文件的[mimeType]
         */
        [formData appendPartWithFileData:data name:@"attachments[]" fileName:fileName mimeType:@"file/zip"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        //上传进度
        // @property int64_t totalUnitCount;     需要下载文件的总大小
        // @property int64_t completedUnitCount; 当前已经下载的大小
        //
        // 给Progress添加监听 KVO
        NSLog(@"%f",1.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
        // 回到主队列刷新UI,用户自定义的进度条
        dispatch_async(dispatch_get_main_queue(), ^{
            hud.progress = 1.0 *
            uploadProgress.completedUnitCount / uploadProgress.totalUnitCount;
        });
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        hud.detailsLabelText = @"上传完成";
        successBlock();
        [hud hide:YES afterDelay:1.0f];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        hud.detailsLabelText = error.localizedDescription;
        failBlock();
        [hud hide:YES afterDelay:1.0f];
    }];
    
}
@end
